package com.yunhe.openapi.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yunhe.common.model.ResultObject;
import com.yunhe.openapi.client.MeasHistoryClient;
import com.yunhe.openapi.client.MeasRealtimeClient;
import com.yunhe.openapi.model.CustomerInfo;
import com.yunhe.openapi.model.MeasRealtime;
import com.yunhe.openapi.service.MeasService;
import com.yunhe.openapi.util.CustomerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 量测数据接口服务
 */

@Service
public class MeasServiceImpl implements MeasService {

    @Autowired
    private MeasRealtimeClient measRealtimeClient;

    @Autowired
    private MeasHistoryClient measHistoryClient;

    @Override
    public List<List<MeasRealtime>> getRealTimeDataAll(String customerId) {
        //根据客户id查询客户的配置信息
        Assert.isTrue(StringUtils.isNotBlank(customerId), "客户id参数异常");
        CustomerInfo info = CustomerUtil.getByCustomerId(customerId);

        //获取此客户编码下所有的企业
        List<List<MeasRealtime>> resList = new ArrayList<>();
        info.getCompanys().forEach(company->{
            resList.add(this.getRealTimeData(customerId, company.getCode(), null));
        });

        return resList;
    }

    /**
     * 获取实时量测数据
     * @param customerId 客户编号
     * @param companyCode 公司编码
     * @param dataCode 点号编码 P,E,UA,UB...  不填默认为yml配置的所有点号
     * @return
     */
    @Override
    public List<MeasRealtime> getRealTimeData(String customerId, String companyCode, String dataCode) {
        //根据客户id查询客户的配置信息
        CustomerInfo info = getCompanyInfo(customerId, companyCode);
        Assert.isTrue(Objects.nonNull(info), "客户id异常");

        //调接口获取点号信息
        Set<String>  pointNumbers = info.getPointNumbers(companyCode, dataCode);
        ResponseEntity<ResultObject> res = measRealtimeClient.getMeasureRealtime(StringUtils.join(pointNumbers, ","));
        Map<String, Double> resMap = (Map<String, Double>) res.getBody().getResults();

        //封装返回数据
        List<MeasRealtime> list = new ArrayList<>();
        resMap.forEach( (pointNumber, v) ->{
            MeasRealtime entity = new MeasRealtime();
            //entity.setPointNumber(k);
            entity.setValue(String.valueOf(v));
            entity.setCompanyName(info.getCompanyName(companyCode));
            entity.setDataCode(info.getDataCoe(pointNumber));
            list.add(entity);
        } );

        return list;
    }

    @Override
    public List<Map<String, Object>> getHistoryData(String customerId, String companyCode, String dataCode, String dtime) {
        //根据客户id查询客户的配置信息
        CustomerInfo info = getCompanyInfo(customerId, companyCode);

        //调接口获取点号信息
        String pointNumbers = StringUtils.join(info.getPointNumbers(companyCode, dataCode), ",");
        //解析时间 格式与内容校验
        dtime = checkDtime(dtime);

        ResponseEntity<ResultObject> res = measHistoryClient.getHistoryData(pointNumbers, dtime);
        List<Map<String, Object>> resList = (List<Map<String, Object>>) res.getBody().getResults();
        for(int i=0; i<resList.size(); i++){
            List<Map<String, Object>> list = (List<Map<String, Object>>) resList.get(i);
            list.forEach(m->{
                m.put("companyName", info.getCompanyName(companyCode));
                String pointNumber = String.valueOf(m.get("pointNumber"));
                m.put("dataCode", info.getDataCoe(pointNumber) );
                m.remove("pointNumber");
                //m.put("pointNumber", null);
            });
        }

        return resList;
    }

    //校验时间格式和内容： long类型，时间差不能超过三天
    private String checkDtime(String dtime) {
        Assert.isTrue(StringUtils.isNotBlank(dtime), "时间参数异常");
        String[] arr = dtime.split(",");
        Long start = Long.valueOf(arr[0]);
        Long end = Long.valueOf(arr[1]);
        Long timeDiff = 259200000L; //1000*60*60*24*3 限制查三天间隔的历史数据
        if(end < start || end-start >timeDiff){ //传入的时间不符要求
            Assert.isTrue(false, "时间参数解析异常，可能超过时间间隔超过三天");
        }
        String startStr = DateUtil.format(new Date(start), "yyyy-MM-dd HH:mm:ss");
        String endStr = DateUtil.format(new Date(end), "yyyy-MM-dd HH:mm:ss");
        return startStr + "," + endStr;
    }

    //根据客户id查询客户的配置信息
    private CustomerInfo getCompanyInfo(String customerId, String companyCode) {
        Assert.isTrue(!StringUtils.isEmpty(customerId), "客户id参数异常");
        Assert.isTrue(!StringUtils.isEmpty(companyCode), "公司编码参数异常");

        CustomerInfo info = CustomerUtil.getByCustomerId(customerId);
        Assert.isTrue(Objects.nonNull(info), "客户id参数异常");
        return info;
    }

}
